package cn.learn.config;


import cn.learn.domain.SysAccount;
import cn.learn.domain.SysPermission;
import cn.learn.service.ISysLoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 设置用户动态信息
 * @author huangyezhan
 * @date 2020年2月17日20:55:57
 */
@Component
public class MyUserDetailService implements UserDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(MyUserDetailService.class);

    @Autowired
    private ISysLoginService sysLoginService;


    /**
     * 根据用户的账号名称，获取用户的账号信息和该账号的角色
     *
     * @param username 账号名称
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("登录用户的账号：[{}]", username);
        SysAccount account = sysLoginService.getAccountByName(username);
        if (account == null) {
            logger.info("没有该用户[{}]", username);
            throw new UsernameNotFoundException("没有该用户！");
        }
        //该用户在正常状态下,才去获取权限
        if(account.isEnabled() && account.isAccountNonExpired() && account.isAccountNonLocked() && account.isCredentialsNonExpired()){
            Set<SysPermission>    permissions = sysLoginService.getPermissionsByAccountId(account.getId());
            Set<GrantedAuthority> authorities = setPermissions(permissions);
            account.setAuthorities(authorities);
        }
        return account;
    }

    /**
     * 设置权限，直接用了权限编码
     *
     * @param permissions 权限
     * @return
     */
    private Set<GrantedAuthority> setPermissions(Set<SysPermission> permissions) {
        Set<GrantedAuthority> authorities = new HashSet<>();
        for (SysPermission permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission.getPermissionCode()));
        }
        return authorities;
    }


}
